package me.zhengjie.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

/**
 * Trans收运系统数据源配置
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryTrans",
        transactionManagerRef = "transactionManagerTrans",
        basePackages = {"me.zhengjie.modules.*.repositoryTrans"})
public class TransDataSourceConfig {

    @Autowired
    @Qualifier("transDataSource")
    private DataSource transDataSource;

    @Resource
    private JpaProperties jpaProperties;

    @Resource
    private HibernateProperties hibernateProperties;

    @Bean(name = "entityManagerTrans")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryTrans(builder).getObject().createEntityManager();
    }

    @Bean(name = "entityManagerFactoryTrans")    //实体工厂
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryTrans(EntityManagerFactoryBuilder builder) {

        return builder.dataSource(transDataSource)
                .properties(getHibernateProperties())
                .packages("me.zhengjie.modules.*.domainTrans")     //实体类所在位置
                .persistenceUnit("transPersistenceUnit")
                .build();
    }

    @Bean(name = "transactionManagerTrans")
    public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryTrans(builder).getObject());
    }

    private Map<String, Object> getHibernateProperties() {
        return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
    }

}